/** @file    SharedTransaction.cpp
 *  @author  Alessandro Polo
 *  @version $Id: SharedTransaction.cpp 2821 2010-08-01 11:44:26Z alex $
 *  @brief
 * File containing methods for the wosh::SharedTransaction class.
 * The header for this class can be found in SharedTransaction.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include <core/SharedTransaction.h>
 #include <core/SharedMemoryDsm.h>
 #include <core/ObjectAllocator.h>
 #include <core/Utilities.h>
 #include <core/Request.h>
 #include <core/Response.h>


using namespace std;
namespace wosh {

 WOSH_REGISTER_INTERFACE(wosh::Transaction, "", 1.01, _static_Transaction)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
Transaction::Transaction( SharedMemoryDsm* dsm_ptr )
	: id(0), timestamp(0), creator_id(0), state(STATE_CREATED), parent(dsm_ptr) {
	this->id = Utilities::randomLong();
	this->timestamp = Utilities::std_time();
	if ( this->parent != NULL )
		this->creator_id = this->parent->getID();
 }

Transaction::Transaction( const Transaction& m )
	: id(m.id), timestamp(m.timestamp), creator_id(m.creator_id), state(m.state), acks(m.acks), parent(m.parent) { }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

int Transaction::invalidateConflits( bool nack_them ) {
	if ( this->parent == NULL ) return -1;
	int count = 0;
	this->parent->getTransactions().transactionBeginWrite();
	tTransactionList::Iterator it;
	const tTransactionList::ConstIterator it_end = this->parent->getTransactions().end();
	for( it=this->parent->getTransactions().begin(); it!=it_end; ++it ) {
		if ( *it == NULL || *it == this ) continue;
		if ( (*it)->isNACKedBySomeone() ) continue; // ignore since already nacked!
		// if is acked by all then we have a state-failure
		// now depends my scope/operation vs current.

	 }

	this->parent->getTransactions().transactionEnd();
	return count;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Transaction& Transaction::operator=(const Transaction& m) {
	if (this == &m) return *this; // same object?

	this->id = m.id;
/*
	this->timestamp = m.timestamp;
	this->creator_id = m.creator_id;
	this->acks = m.acks;
	this->parent = m.parent;

*/

	return *this;
 }

bool Transaction::operator==(const Transaction &other) const {
	if ( this->id != other.id )
		return false;
	if ( this->acks.size() != other.acks.size()  )
		return false;
	return true;
 }

Response* Transaction::replyACK() const {
	return new Response(_SharedMemoryDsm_METHOD_transaction, new Variant(this->id), WRET_OK);
 }
Response* Transaction::replyNACK() const {
	return new Response(_SharedMemoryDsm_METHOD_transaction, new Variant(this->id), WRET_ERR_INTERNAL);
 }

short Transaction::getResponseOf( long agent_id ) const {
	std::map<long, short>::const_iterator it = this->acks.find(agent_id);
	if ( it == this->acks.end() )
		return Transaction::NO_REPLY;
	return it->second;
 }


int Transaction::countAgentsFlag( short ack_option ) const {
	int count = 0;
	std::map<long, short>::const_iterator it;
	const std::map<long, short>::const_iterator it_end = this->acks.end();
	for( it=this->acks.begin(); it!=it_end; ++it ) {
		if ( it->second == ack_option )
			++count;
	 }
	return count;
 }

bool Transaction::isTimedOut() const {
	return false;
 }

std::string Transaction::toString() const {
	return Utilities::format("Transaction#%"PRId64" by %ld (%d/%d/%d of %d)", this->id, this->creator_id,
								getACKsCount(),getNACKsCount(),getNoReplyCount(), this->acks.size() );
 }

bool Transaction::updateHash( DataHashContext* hash_context ) const {
	if ( hash_context == NULL ) return false;
	bool ret = true;
	ret = hash_context->update( this->id ) & ret;
	ret = hash_context->update( this->timestamp ) & ret;
	ret = hash_context->update( this->creator_id ) & ret;
	ret = hash_context->update( this->state ) & ret;
	return ret;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 WOSH_REGISTER(wosh::TransactionAgentDeath, "wosh::Transaction", 1.01, _static_TransactionAgentDeath)

TransactionAgentDeath::TransactionAgentDeath( SharedMemoryDsm* parent )
	: Transaction(parent), died_agent_id(0) {
	if ( parent != NULL )
		this->died_agent_id = parent->getID();
 }

WRESULT TransactionAgentDeath::precommit() {
	this->state = Transaction::STATE_PRECOMMITTED | Transaction::STATE_FAILED;
	if ( this->parent == NULL ) return WRET_ERR_PARAM;
	if ( this->died_agent_id == 0 ) return WRET_ERR_PARAM;
	this->parent->getAgents().transactionBeginWrite();
	// fix my group-view
	tLongSharedMemoryInfoMap::ConstIterator ita;
	const tLongSharedMemoryInfoMap::ConstIterator ita_end = this->parent->getAgents().end();
	for( ita=this->parent->getAgents().begin(); ita!=ita_end; ++ita ) {
		this->acks[ita->first] = Transaction::NO_REPLY;
	 }
	// a death-certificate intrinsically is acked by died agent, especially if its the transaction's creator
	if ( this->creator_id == this->died_agent_id )
		this->acks[this->died_agent_id] = Transaction::ACKED;
	// flag agent as died
	SharedMemoryInfo* agent_slot = this->parent->getAgents().find(this->died_agent_id);
	if ( agent_slot == NULL ) {
		this->parent->getAgents().transactionEnd();
		return WRET_ERR_INTERNAL;
	 }
//	agent_slot->died = true;
	this->parent->getAgents().transactionEnd();
	this->state = Transaction::STATE_PRECOMMITTED;
	return WRET_OK;
 }
	
WRESULT TransactionAgentDeath::commit() {
	this->state = Transaction::STATE_COMMITTED | Transaction::STATE_FAILED;
	if ( this->parent == NULL ) return WRET_ERR_PARAM;
	if ( this->died_agent_id == 0 ) return WRET_ERR_PARAM;
	this->parent->getAgents().transactionBeginWrite();
	SharedMemoryInfo* agent_slot = this->parent->getAgents().find(this->died_agent_id);
	if ( agent_slot == NULL ) {
		this->parent->getAgents().transactionEnd();
		return WRET_ERR_INTERNAL;
	 }
//	if ( !agent_slot->died ) { // something weird happened!?
//		this->parent->getAgents().transactionEnd();
//		return WRET_ERR_ILLEGAL_USE;
//	 }
	this->parent->getAgents().erase(this->died_agent_id, true);
	this->parent->getAgents().transactionEnd();
	this->state = Transaction::STATE_COMMITTED;
	return WRET_OK;
 }
WRESULT TransactionAgentDeath::rollback() {
	this->state = Transaction::STATE_ROLLEDBACK | Transaction::STATE_FAILED;
	if ( this->parent == NULL ) return WRET_ERR_PARAM;
	if ( this->died_agent_id == 0 ) return WRET_ERR_PARAM;
	this->parent->getAgents().transactionBeginWrite();
	SharedMemoryInfo* agent_slot = this->parent->getAgents().find(this->died_agent_id);
	if ( agent_slot == NULL ) {
		this->parent->getAgents().transactionEnd();
		return WRET_ERR_INTERNAL;
	 }
//	agent_slot->died = false;
	this->parent->getAgents().transactionEnd();
	this->state = Transaction::STATE_ROLLEDBACK;
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

TransactionAgentDeath& TransactionAgentDeath::operator=(const TransactionAgentDeath& m) {
	if (this == &m) return *this; // same object?
	(wosh::Transaction&)*this = (const wosh::Transaction&)m;

	return *this;
 }

//std::string TransactionAgentDeath::toString() const {
//	return "TransactionAgentDeath";
// }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

}; // namespace wosh
